package untils

import (
	"fmt"
	"github.com/golang-jwt/jwt/v4"
	"time"
)

// 自定义JWt
type CustomClaims struct {
	Uid uint `json:"uid"`
	jwt.RegisteredClaims
}

// 生成登录令牌（有效期7天）
func JWTGenerate(uid uint) (string, error) {
	secret := []byte("laoyuegou-social-secret")
	claims := CustomClaims{
		Uid: uid,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(7 * 24 * time.Hour)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(secret)
}

// 验签，取uid
func JWTParse(tokenString string) (uint, error) {
	secret := []byte("laoyuegou-social-secret")
	token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(t *jwt.Token) (interface{}, error) {
		return secret, nil
	})
	if err != nil {
		return 0, err
	}
	if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
		return claims.Uid, nil
	}
	return 0, fmt.Errorf("invalid token")
}
